<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="85px"
      class="form-search"
    >
      <SearchTool
        :code="{
          factory: 'factoryCode',
          workshop: 'workshopCode',
          line: 'productionLine',
          section: 'processSection',
        }"
        v-model:factory="queryParams.factoryCode"
        v-model:workshop="queryParams.workshopCode"
        v-model:line="queryParams.productionLine"
        v-model:section="queryParams.processSection"
      ></SearchTool>
      <el-form-item label="设备类型" prop="type">
        <et-select
          :api="listType"
          v-model="queryParams.type"
          v-model:name="form.type"
          clearable
          filterable
          keyValue="code"
          labelValue="name"
        ></et-select>
      </el-form-item>
      <el-form-item label="设备名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入设备名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入设备编号"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="状态"
          clearable
          filterable
          style="width: 240px"
        >
          <el-option
            v-for="dict in equipment_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['base:prodEquipment:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['base:prodEquipment:edit']"
          >编辑</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['base:prodEquipment:remove']"
          >删除</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          :loading="syncLoading"
          type="warning"
          plain
          icon="Refresh"
          @click="handleSync"
          v-hasPermi="['base:prodEquipment:sync']"
          >同步EAM数据</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="typeList"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        :selectable="selectable"
        align="center"
      />
      <el-table-column
        label="设备编号"
        align="center"
        prop="code"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <el-link type="primary" @click="handleDetail(scope.row)">{{
            scope.row.code
          }}</el-link>
        </template>
      </el-table-column>

      <el-table-column
        label="设备名称"
        align="center"
        prop="name"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="设备类型"
        align="center"
        prop="typeName"
        :show-overflow-tooltip="true"
      />

      <el-table-column
        label="工厂"
        align="center"
        prop="factoryName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="工段"
        align="center"
        prop="workshopName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="产线"
        align="center"
        prop="productionLineName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="工艺段"
        align="center"
        prop="processSectionName"
        :show-overflow-tooltip="true"
      />

      <el-table-column
        label="厂家"
        align="center"
        prop="manufacturer"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="设备型号"
        align="center"
        prop="model"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="关联工序"
        align="center"
        prop="processName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="来源"
        align="center"
        prop="source"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <dict-tag :options="equip_source" :value="scope.row.source" />
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="equipment_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            v-if="scope.row.source !== 'EAM'"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['base:prodEquipment:edit']"
            >编辑</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            v-if="scope.row.source !== 'EAM'"
            @click="handleDelete(scope.row)"
            v-hasPermi="['base:prodEquipment:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      :close-on-click-modal="false"
      width="700px"
      append-to-body
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="设备编号" prop="code">
          <code-input
            v-model="form.code"
            code="EQUIPMENT_CODE"
            :disabled="!!form.id"
            placeholder="请输入设备编号"
          />
        </el-form-item>
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入设备名称" />
        </el-form-item>
        <SearchTool
          :code="{
            factory: 'factoryCode',
            workshop: 'workshopCode',
            line: 'productionLine',
            section: 'processSection',
          }"
          v-model:factory="form.factoryCode"
          v-model:factoryName="form.factoryName"
          v-model:workshop="form.workshopCode"
          v-model:workshopName="form.workshopName"
          v-model:line="form.productionLineCode"
          v-model:lineName="form.productionLineName"
          v-model:section="form.processSectionCode"
          v-model:sectionName="form.processSectionName"
        ></SearchTool>

        <el-form-item label="设备类型" prop="type">
          <et-select
            :api="listType"
            v-model="form.type"
            v-model:name="form.typeName"
            keyValue="code"
            labelValue="name"
          ></et-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in equipment_status"
              :key="dict.value"
              :value="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="厂家" prop="manufacturer">
          <el-input v-model="form.manufacturer" placeholder="请输入厂家" />
        </el-form-item>
        <el-form-item label="设备型号" prop="model">
          <el-input v-model="form.model" placeholder="请输入设备型号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Dict">
import {
  listEquipment,
  getEquipment,
  delEquipment,
  addEquipment,
  updateEquipment,
  syncEAMEqptList,
} from "@/api/base/equipment/equipmentApi";
import { listType } from "@/api/base/equipment/equipmentTypeApi";
import DetailData from "./data";
import SearchTool from "@/components/SearchTool";
const selectable = (row) => row.source !== "EAM";
const { proxy } = getCurrentInstance();
const { sys_normal_disable, equip_source, equipment_status } = proxy.useDict(
  "sys_normal_disable",
  "equip_source",
  "equipment_status"
);
const syncLoading = ref(false);
const typeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    code: undefined,
    name: undefined,
    status: undefined,
  },
  rules: {
    name: [{ required: true, message: "请输入设备名称!", trigger: "blur" }],
    typeCode: [
      {
        required: true,
        message: "请输入设备类型!",
        trigger: "blur",
      },
    ],
    code: [{ required: true, message: "请输入设备编号!", trigger: "blur" }],
    code: [{ required: true, message: "请输入设备编码!", trigger: "blur" }],
    factoryCode: [{ required: true, message: "请选择工厂!", trigger: "blur" }],
    workshopCode: [{ required: true, message: "请选择工段!", trigger: "blur" }],
    type: [{ required: true, message: "请选择设备类型!", trigger: "blur" }],
    segmentCode: [
      { required: true, message: "请选择工艺段!", trigger: "blur" },
    ],
    status: [{ required: true, message: "请输入设备状态!", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询字典类型列表 */
function getList() {
  loading.value = true;
  listEquipment(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (response) => {
      typeList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    }
  );
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
function handleSync() {
  syncLoading.value = true;
  syncEAMEqptList()
    .then((res) => {
      proxy.$modal.msgSuccess("同步成功");

      syncLoading.value = false;
      getList();
    })
    .catch(() => {
      syncLoading.value = false;
    });
}
function handleDetail(row) {
  proxy.subPage(DetailData, { title: "设备详情", data: row });
}

function deptChange(type) {
  const deptLevel = [
    "factoryCode",
    "workshopCode",
    "productionLineCode",
    "processSectionCode",
  ];
  let isCurrent = false;
  for (let index = 0; index < deptLevel.length; index++) {
    const ele = deptLevel[index];
    if (isCurrent) {
      form.value[ele] = "";
      continue;
    }
    isCurrent = ele === type;
  }

  // if (type === "processSectionCode") {
  //   form.value.typeCode = "";
  //   form.value.type = "";
  // }
}

/** 表单重置 */
function reset() {
  form.value = {
    name: undefined,
    type: undefined,
    code: undefined,
    model: undefined,
    factory: undefined,
    workshopCode: undefined,
    status: undefined,
    remark: undefined,
  };
  proxy.resetForm("formRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加设备";
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const equipId = row.id || ids.value;
  getEquipment(equipId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "编辑设备信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        updateEquipment(form.value).then((response) => {
          proxy.$modal.msgSuccess("编辑成功");
          open.value = false;
          getList();
        });
      } else {
        addEquipment(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const idList = row.id || ids.value.join(",");
  const codes =
    row.code ||
    ids.value
      .map((id) => typeList.value.find((item) => item.id === id)?.code)
      .join(", ");

  proxy.$modal
    .confirm('是否确认删除设备编号为"' + codes + '"的数据项？')
    .then(function () {
      return delEquipment({ ids: idList });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

getList();
</script>
